import { useState, useEffect, useContext, useRef } from 'react'
import PanelLeft from '../../../../../common/PanelLeft';
import DarkBtn from '../../../../../common/DarkBtn';
import DarkCard from '../../../../../common/DarkCard';
import { Button, Col, Collapse, Row, Select, Space, Tooltip, Tree } from 'antd';
import GlobalContext from '../../../../../../utils/GlobalContext';
import useBusinessMap from '../../../../../common/BusinessMap/useBusinessMap';
import { Vector as VectorLayer } from 'ol/layer'
import { Vector as VectorSource } from 'ol/source'
import Api from '../../../../../../utils/api';
import FetchHelper from '../../../../../../utils/helper/fetch-helper';
import { dataToFeature, navByWkt } from '../../../../../../utils/helper/mapHelper';
import Style from 'ol/style/Style';
import Stroke from 'ol/style/Stroke';
import Fill from 'ol/style/Fill';
import Circle from 'ol/style/Circle';
import CztApi from '../../../../../../utils/apis/CztApi';
import { LeftOutlined, MenuFoldOutlined, MenuUnfoldOutlined } from '@ant-design/icons';
import useMapGlobal from '../../../../../common/BusinessMap/useMapGlobal';
import JzzyApi from '../../../../../../utils/apis/JzzyApi';
import ZhfxApi from '../../../../../../utils/apis/ZhfxApi';
import ZdfhApi from '../../../../../../utils/apis/ZdfhApi';
import Zhyxzhfx from '../Zhyxzhfx';
import LittleTitle from '../../../../../common/LittleTitle';
import Cztzhfx from '../Cztzhfx';
import Cszhfx from '../Cszhfx';
import Jznlfx from '../Jznlfx';
import Zzfxfx from '../Zzfxfx';
import Yxdjyp from '../Yxdjyp';
import { Overlay } from 'ol';
import bootstrap from 'bootstrap/dist/js/bootstrap.bundle';

const generateData = (datas, dl) => {
    datas.forEach(data => {
        data.dl = dl;
        if (data.children) {
            generateData(data.children, dl)
        }
    });
    return datas
}

function Popup({ qp, ttipJjx,position }) {
    return (
        <div>
            <div style={{
                position: 'absolute',
                left: `${position.x}px`,
                top: `${position.y - 50}px`,
                display: 'inline-block',
                whiteSpace: 'nowrap',
                borderRadius: 10,/* 设置圆角半径 */
                backgroundColor: 'black', /* 设置背景色为黑色 */
                padding: 10, /* 可选：添加内边距以增加可读性 */
                color: 'white',/* 可选：设置文本颜色为白色 */
            }} >
                {qp}<br />{ttipJjx ? '警戒线:' + ttipJjx : " "}
            </div>
        </div>
    );
}

export default function LeftPanel(props) {
    // const { layerDatas } = useContext(GlobalContext)
    const map = useBusinessMap();
    const { onComplete } = props;

    const [visible, setVisible] = useState(true);
    const [type, setType] = useState();

    /* 
    --地图切换时清除地图上现有的"layerName" === 'rangeDisplayIcon'的图标，但未完成的网络请求会在切换后把后续图标继续加载在地图上，待解决
    */
    useEffect(() => {
        const allLayers = map?.getLayers().getArray();
        if (allLayers) {
            [...allLayers].forEach(l => {
                if (l?.get("layerName") === 'rangeDisplayIcon')
                    map.removeLayer(l);
            })
        }
    }, [type, map])
    // useEffect(() => {

    //         onComplete?.(null)

    // }, [type,onComplete])

    const [position, setPosition] = useState({ x: 0, y: 0 });

    useEffect(() => {
      const handleMouseMove = (event) => {
        setPosition({ x: event.pageX, y: event.pageY });
        
      };
  
      window.addEventListener('mousemove', handleMouseMove);
  
      return () => {
        window.removeEventListener('mousemove', handleMouseMove);
      };
    }, []);

    const [qp, setqp] = useState();
    const [ttipJjx, setTtipJjx] = useState();
    const popupRef = useRef(null);
    useEffect(() => {
        if (map) {
            const handler = evt => {
                const popup = new Overlay({
                    element: popupRef.current,
                });
                map.addOverlay(popup);
                const features = map.getFeaturesAtPixel(evt.pixel);
                // console.log('features',features)
                const coordinate = features?.find(feature => feature.get('yhlb'))?.getGeometry()?.getCoordinates();
                const coordinate1 = features?.find(feature => feature.get('cztdl'))?.getGeometry()?.getCoordinates();
                const coordinate2 = features?.find(feature => feature.get('jzzydl'))?.getGeometry()?.getCoordinates();
                const coordinate3 = features?.find(feature => feature.get('cszhlx'))?.getGeometry()?.getCoordinates();
                // console.log('coordinate',coordinate)
                if (coordinate) {
                    popup.setPosition(coordinate);
                } else if (coordinate1) {
                    popup.setPosition(coordinate1);
                } else if (coordinate2) {
                    popup.setPosition(coordinate2);
                } else {
                    popup.setPosition(coordinate3);
                }
                const item = features?.find(feature => feature.get('yhlb'))?.getProperties();
                const item1 = features?.find(feature => feature.get('cztdl'))?.getProperties();
                const item2 = features?.find(feature => feature.get('jzzydl'))?.getProperties();
                const item3 = features?.find(feature => feature.get('cszhlx'))?.getProperties();
                const tooltip = item?.yhmc;
                // const ttip = item?.jcjjx;
                const tooltip1 = item1?.cztmc;
                const ttip1 = item1?.fhjd;
                const tooltip2 = item2?.jzzymc;
                const tooltip3 = item3?.cszhmc;

                // const ttip2 = item2?.fhjd;
                if (item) {
                    setqp(tooltip);
                    // setTtipJjx(ttip)
                } else if (tooltip1) {
                    setqp(tooltip1);
                    // setTtipJjx(ttip1)
                } else if (tooltip2) {
                    setqp(tooltip2);
                    // setTtipJjx(ttip2)
                } else {
                    setqp(tooltip3);
                }
                //console.log('item',item)


                let popover = bootstrap.Popover.getInstance(popupRef.current);
                if (popover) {
                    popover.dispose();
                }
                popover = new bootstrap.Popover(popupRef.current, {
                    animation: false,
                    container: popupRef.current,
                    content: null,
                    html: true,
                    placement: 'right'
                });
                popover.show();
            }
            map.on('pointermove', handler);
            return () => {
                map.un('pointermove', handler);
            }
        }
    }, [map])

    return <div className='layout-v' style={{
        position: "absolute",
        left: 20,
        top: 20,
        bottom: 20,
        overflow: 'auto'
    }}>
        {!visible && <DarkBtn placement="right" title="风险分析" icon={<MenuUnfoldOutlined />} onClick={e => {
            setVisible(true)
        }}></DarkBtn>}
        {visible && <>
            <DarkCard className="layout-h center" style={{
                width: 300,
                // height: 42,
                marginBottom: 10,
                fontSize: 20,
                fontWeight: 'bold',
            }}>
                <div className='fill'>风险分析</div>
                <Button title="收起" icon={<MenuFoldOutlined />} type={'text'} onClick={e => {
                    setVisible(false)
                }}></Button>
            </DarkCard>
            <DarkCard className="fill h0" style={{
                width: 300,
                overflow: "auto",
                // height: 300
            }}>
                <Space direction='vertical' style={{
                    width: "100%",
                    overflow: "hidden"
                }}>

                    <LittleTitle fontSize={16} icon={false}>选择分析信息</LittleTitle>
                    <div className='layout-h center'>
                        <div>类型：</div>
                        <div className='fill'>
                            <Select value={type} onChange={value => {
                                setType(value);
                            }} style={{
                                width: "100%"
                            }} options={[{
                                label: '灾害影响综合分析',
                                value: 'zhyxzhfx'
                            }, {
                                label: '致灾风险分析',
                                value: 'zzfxfx'
                            }, {
                                label: '承灾体综合分析',
                                value: 'cztzhfx'
                            }, {
                                label: '次生灾害分析',
                                value: 'cszhfx'
                            }, {
                                label: '减灾能力分析',
                                value: 'jznlfx'
                            }, {
                                label: '影响叠加研判',
                                value: 'yxdjyp'
                            }]}></Select>
                        </div>
                    </div>
                    {type === 'zhyxzhfx' && <Zhyxzhfx onComplete={data => {
                        props.onComplete?.({
                            type: type,
                            data,
                            newWkt: data.newWkt
                        })
                    }}
                    />}
                    {
                        type === 'zzfxfx' && <Zzfxfx onComplete={(data, geom) => {
                            props.onComplete?.({
                                type: type,
                                data,
                                geom: geom
                            })
                        }} />
                    }
                    {type === 'cztzhfx' && <Cztzhfx onComplete={(data, geom) => {
                        props.onComplete?.({
                            type: type,
                            data,
                            geom: geom
                        })
                    }} />}
                    {type === 'cszhfx' && <Cszhfx onComplete={(data, geom) => {
                        props.onComplete?.({
                            type: type,
                            data,
                            geom: geom
                        })
                    }} />}
                    {type === 'jznlfx' && <Jznlfx onComplete={(data, geom) => {
                        props.onComplete?.({
                            type: type,
                            data,
                            geom: geom
                        })
                    }} />}
                    {type === 'yxdjyp' && <Yxdjyp onComplete={(resps) => {
                        props.onComplete?.({
                            type,
                            data: resps
                        })
                    }} />}

                </Space>
            </DarkCard>
        </>}
        {qp && <Popup ttipJjx={ttipJjx} qp={qp} ref={popupRef} position={position} />}

    </div>;
}